package com.example.utils;

import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @Description: SSL工具类, 发送https请求时忽略安全证书验证
 * @Auther: Swain
 * @Date: 2021/1/18 15:43
 * @Version 1.0.0
 */
@Log4j2
public class SSLUtils {

    public static void init() {
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            log.error("忽略安全证书检测失败", e);
        }
    }
}
